package com.lib.okhttp.reqbody;

import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;

import com.lib.okhttp.NetClient.InnerHandler;
import com.lib.utils.CloseUtils;
import com.lib.utils.XLog;

import java.io.File;
import java.lang.ref.WeakReference;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

/**
 * 创建带进度的RequestBody
 */
public class FileRequestBody extends RequestBody {

    private MediaType mMediaType;
    private Handler mHandler;
    private File mFile;

    /**
     * @param mediaType MediaType
     * @param file      准备上传的文件
     */
    public FileRequestBody(MediaType mediaType, Handler handler, File file) {
        mMediaType = mediaType;
        mFile = file;
        mHandler = new WeakReference<>(handler).get();
    }

    @Override
    public MediaType contentType() {

        return mMediaType;
    }

    @Override
    public long contentLength() {

        return mFile.length();
    }

    @Override
    public void writeTo(BufferedSink sink) {
        long total = mFile.length();

        long current = 0;
        Source source = null;

        long byteCount = 1024;
        Buffer buf = new Buffer();
        try {
            source = Okio.source(mFile);
            long readCount;
            while ((readCount = source.read(buf, byteCount)) != -1) {
                XLog.i("readCount->" + readCount);

                sink.write(buf, readCount);

                current += readCount;
                if (mHandler != null) {
                    if (current >= total) {
                        Message.obtain(mHandler, InnerHandler.MSG_PROGRESS, 100).sendToTarget();
                    } else {
                        int percentage = (int) ((100.0 * current) / total);
                        Message.obtain(mHandler, InnerHandler.MSG_PROGRESS, percentage).sendToTarget();
                    }
                }
                /*限速用*/
                SystemClock.sleep(100);
            }
        } catch (Exception ignored) {
        } finally {
            CloseUtils.closeIOQuietly(buf, source);
        }
    }
}